import requests
import json

class word():

    def download(self,url):
        try:
            response = requests.get(url)
            response.encoding = "utf-8"
            json_dict = response.json()

            page_list = json_dict["data"]["htmlUrls"]["json"]
            title = json_dict["data"]["docId"]

            file = f"e:/{title}.word"

            open(file, "w").close()
            for index, page in enumerate(page_list, start=1):
                page_url = page["pageLoadUrl"]
                resp = requests.get(page_url)
                data = resp.text.split("(", 1)[1][:-1]
                json_data = json.loads(data)
                for x in json_data["body"]:
                    text = x["c"]
                    if type(text) is str:
                        with open(file, "a", encoding="utf-8") as f:
                            f.write(text)
                print(f"download: {index}")
            return True
        except Exception as e:
            print(index, e)
            print("failed")
            return False

    def create_url(self, doc_id):
        url = "https://wenku.baidu.com/ndocview/readerinfo?doc_id=" + doc_id + "&docId=" + doc_id + "&type=html&clientType=100&pn=0&isFromBdSearch=0&srcRef=&rn=100&powerId=2&bizName=mainPc"
        return url